//
//  MainViewController.swift
//  WeoboWithSteveLi
//
//  Created by SteveLi on 2017/9/18.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加控制器，并不会创建 tabbar 中的按钮
        //懒加载是无处不在的，所有的控件都是延迟创建的
      addChildViewControllers()
        print(tabBar.subviews)
        
        setupComposedButton()
    }
    override func viewWillAppear(_ animated: Bool) {
        //会创建 tabbar 中的所有控制器对应的按钮
        super.viewWillAppear(animated)
        //将撰写按钮弄到最前面
        tabBar.bringSubview(toFront: composedButton)
        
        print(tabBar.subviews)
    }
    
    //懒加载控件
   lazy var composedButton: UIButton = {
        //自定义样式的按钮
        let button = UIButton()
        button.setImage(UIImage.init(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
          button.setImage(UIImage.init(named: "tabbar_compose_icon_hightlighted"), for: UIControlState.highlighted)
          button.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage.init(named: "tabbar_compose_button_hightlighted"), for: UIControlState.highlighted)
    //会根据背景图片的大小调整尺寸
        button.sizeToFit()
    
        return button
    }()
    
}

//设置界面
extension MainViewController{
    //设置撰写按钮
    func setupComposedButton() {
        
        //1.添加按钮
        tabBar.addSubview(composedButton)
        //2.跳转按钮
        let count = childViewControllers.count
        // -1 让按钮宽一点点，能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        composedButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
    }
    
    //添加所有的控制器
   func addChildViewControllers() {
    //设置 tintColor ---图片的渲染颜色
    //性能提升的技巧  如果能用颜色解决，就不建议使用图片
    tabBar.tintColor = UIColor.orange
    addChildViewController(vc: HomeTableViewController(), title: "首页", imageName: "tabbar_home")
    addChildViewController(vc: MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
    addChildViewController(UIViewController())
    addChildViewController(vc: DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
    addChildViewController(vc: ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    //添加控制器
    private func addChildViewController(vc: UIViewController,title: String ,imageName: String) {
        //设置标题
        vc.title = title
        //设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        //导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
        
    }
}
